import {Body, Controller, Get, HttpStatus, Post, Query, Res} from '@nestjs/common';
import {Response} from 'express';
import {CommonRedisService} from '../service/common.redis.service';
import {CommonResponseDto} from '../dto/common.response.dto';
import {ResCode, UserStatus} from '../common/constants';
import AppConfig from 'config/app.config';
import {decrypt, encrypt, generateRandomTokenBase64, getModelConfigList} from "../common/common";
import {uuid} from "../common/utils";


@Controller('api/auth')
export class AuthController {
    constructor(private readonly commonRedisService: CommonRedisService) {}

    @Post('/login')
    async login(@Body() params: { userAccount: string, userPassword: string }, @Res({ passthrough: true }) res: Response) {
        console.log(params)
        res.status(HttpStatus.OK);
        if (!params.userAccount || !params.userPassword) {
            return new CommonResponseDto(ResCode.ERROR, '缺少参数')
        }
        if (params.userAccount !== 'admin' || params.userPassword !== '252205e8054f39a5af284f5d9ea04133f4fb933e1e8e8bd29eead75780f3eee4') {
            return new CommonResponseDto(ResCode.ERROR, '用户名密码错误')
        }
        const token = encrypt('admin_'+uuid(16), AppConfig.AdminSecretKey)
        await this.commonRedisService.set(AppConfig.AdminHeaderKey, token, AppConfig.AdminTokenExpireSec)
        return new CommonResponseDto(ResCode.OK, 'success', {
            user: {
                userId: 'admin',
                userAccount: 'admin'
            },
            token
        })
    }

    @Post('/create-api-token')
    async createApiToken(@Body() params: { userId: string }, @Res({ passthrough: true }) res: Response) {
        console.log(params)
        res.status(HttpStatus.OK);
        if (!params.userId) {
            return new CommonResponseDto(ResCode.ERROR, '缺少参数userId')
        }
        const token = encrypt(`${params.userId}_${uuid(32)}`, AppConfig.ApiTokenSecretKey)
        await this.commonRedisService.set(AppConfig.ApiHeaderKey + '_' + params.userId, token, AppConfig.ApiTokenExpireSec)
        return new CommonResponseDto(ResCode.OK, 'success', {token})
    }

    @Post('/get-api-token')
    async getApiToken(@Body() params: { userId: string }, @Res({ passthrough: true }) res: Response) {
        console.log(params)
        res.status(HttpStatus.OK);
        if (!params.userId) {
            return new CommonResponseDto(ResCode.ERROR, '缺少参数userId')
        }
        const token = await this.commonRedisService.get(AppConfig.ApiHeaderKey + '_' + params.userId)
        if (token) {
            return new CommonResponseDto(ResCode.OK, 'success', {token})
        }
        return new CommonResponseDto(ResCode.ERROR, 'Token不存在')
    }

    @Get('/model-list')
    async getModelList(@Res({ passthrough: true }) res: Response) {
        res.status(HttpStatus.OK);
        return new CommonResponseDto(ResCode.OK, 'success', AppConfig.ModelList)
    }
}
